
/*

   KOMBINE   Combine a set of frames.
   Copyright (C) 2000-x  Filip Hroch, Masaryk University, Brno, CZ

   This is a wrapper from UNIX-like environment with std. inputs,
   environment and command line options to the Fortran file input
   plain world.

   $Id$

*/

#include "cwrap.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>

/* default output filename */
#define NAME "kombine.fits"

void help();
void genopt();

int main(int argc,char *argv[])
{
  FILE *fp,*p;
  char *namsci = NULL, *mask = NAME;
  char **sci;
  char *j,*buf;
  double scale = -1.0;
  int norm = 0;
  int interpol = 0;
  int n,i,bitpix = 0;
  int stdinput = 0;
  int nsci = 0;
  int maxlen = 0;
  int flux = 0;

  fprintf(stdout,"KOMBINE Version 0.4, Copyright (C) 1997-08 F.Hroch, Masaryk University,Brno,CZ\n\n");

  if( argc == 1 ) {
    help();
    return(0);
  }    

  if( (sci = malloc(sizeof(void *)*argc)) == NULL ) 
    exitus(__FILE__,__LINE__,errno);

  for( i = 1; i < argc; i++) {

    /* dir file */
    if( (j = strstr(argv[i],"@")) != NULL ) {
      if( strlen(argv[i]) == 1 )
	stdinput = 1;
      else 
	namsci = j + strlen("@");
    }

    /* interpolation */
    else if( (j = strstr(argv[i],"interpol=")) && 
	      (sscanf(j+strlen("interpol="),"%d",&interpol) == 1) )
      ;

    /* scale */
    else if( (j = strstr(argv[i],"scale=")) && 
	      (sscanf(j+strlen("scale="),"%lf",&scale) == 1) )
      ;

    /* normalisation */
    else if( (j = strstr(argv[i],"norm=")) != NULL ) {
      if( strstr(j+strlen("norm="),"sky") )
        norm = 2;
      if( strstr(j+strlen("norm="),"mean") )
        norm = 1;
    }


    /* bitpix */
    else if( (j = strstr(argv[i],"bitpix=")) && 
	      (sscanf(j+strlen("bitpix="),"%d",&bitpix) == 1) )
      ;

    /* flux */
    else if( (j = strstr(argv[i],"flux=")) && strcmp(j+strlen("flux="),"y")==0)
      flux = 1;

    /* mask of output file */
    else if( (j = strstr(argv[i],"mask=")) != NULL )
      mask = j + strlen("mask=");

    /* license */
    else if( strcmp(argv[i],"-L") == 0 ) {
      licence();
      return(0);
    }

    /* help */
    else if( strcmp(argv[i],"-h") == 0 || strcmp(argv[i],"--help") ==0 ){
      help();
      return(0);
    }

    /* generate option file */
    else if( strcmp(argv[i],"-g") == 0 ){
      genopt();
      return(0);
    }

    /* all others are images to autoflat */
    else {
      sci[nsci] = argv[i];
      nsci = nsci + 1;
      n = strlen(argv[i]);
      if( n > maxlen ) maxlen = n+2;
    }
    
  } 

  /* run a fortran code */
  if( (p = popen("skombine.bin","w")) == NULL ) {
    fprintf(stderr,"%s\n",strerror(errno));
    exit(1);
  }

  /* form the first line to subprocess */
  /* "'kombine.fits' 1.0  0 0 0 0"*/
  fprintf(p,"'%s' %lf %d %d %d %d\n",mask,scale,bitpix,norm,interpol,flux);

  /* read image names from command line */
  if( nsci > 0 ) {

    for( i = 0; i < nsci; i++ )
      fprintf(p,"'%s'\n",sci[i]);

  }
  free(sci);

  /* image names from file or stdin */
  if( namsci || stdinput ) {            
    
    if ( stdinput )
      fp = stdin;
    else if( namsci && (fp = fopen(namsci,"r")) == NULL ) {
      fprintf(stderr,"File not found: %s.\n",namsci);
      return(1);
    }

    while( (buf = fgetline(fp,&n)) ) {
      fprintf(p,"'%s'\n",buf);
      free(buf);
    }
    fclose(fp);
  }

  pclose(p);

  return(0);
}

void help()
{
  printf("%s\n\n%s\n\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
	 "KOMBINE  Combine a set of frames.",
	 "Usage:kombine [@dirfile] [scale=1] [interpol=0] [bitpix=-32] [image1] ...",
	 "@dirfile= file with image names to process, no wildcards *,?",
	 "          (use only '@' to read image names from standard input)",
	 "scale= scale to size by specified factor",
	 "interpol= interpolation by 0..no,1..bilinear,2..bicubic,3..bspline",
	 "norm=[mean|sky] normalisation: mean..sum/n, sky=1",
	 "flux=[y|n] normalize flux",
	 "bitpix= BITPIX of output image",
	 "image1...= name(s) of simple image(s) to process");
  printf("mask= output filename (default=%s)\n",NAME);
  printf("%s\n%s\n%s\n%s\n\n",
	 "options:",
	 "\t-g\t generate an example of a parameter file",
	 "\t-h\t give this help",
	 "\t-L\t display software license");
}

void genopt()
{
  FILE *f;
  char *optname = "kombine.opt";
  struct stat s;

  if( stat(optname,&s) == 0 && S_ISREG(s.st_mode) ) {
    fprintf(stderr,"Option parameter file already exist. No new one created.\n");
    exit(1);
  }

  if( (f = fopen(optname,"w")) ) {
    fprintf(f,"Output filename = kombine.fits\n");
    fprintf(f,"Output normalized by = '' ! 'mean' or 'sky' \n");
    fprintf(f,"Multiply flux = .false.\n");
    fprintf(f,"Method of interpolation = 0\n");
    fprintf(f,"Rescale factor = 1\n");
    fprintf(f,"Output height = -1\n");
    fprintf(f,"Output width = -1\n");
    fprintf(f,"Output BITPIX = 0\n");
    fprintf(f,"Key DATE-OBS = 'DATE-OBS'\n");
    fprintf(f,"Key EXPTIME = 'EXPTIME'\n");
    fprintf(f,"Key FILTER = 'FILTER'\n");
    fclose(f);
  }
  else {
    fprintf(stderr,"%s\n",strerror(errno));
    exit(1);
  }
}
